/**
 * 商品流程验证工具
 * 用于验证商品流程修复的效果
 */

import productValidator from './productDataValidator'
import { handleError } from './errorHandler'
import loadingManager from './loadingManager'

class ProductFlowValidator {
  constructor() {
    this.testResults = []
    this.validationRules = [
      {
        name: '商品数据验证',
        test: this.testProductDataValidation.bind(this)
      },
      {
        name: 'null值处理',
        test: this.testNullValueHandling.bind(this)
      },
      {
        name: '错误处理',
        test: this.testErrorHandling.bind(this)
      },
      {
        name: '加载状态管理',
        test: this.testLoadingManagement.bind(this)
      },
      {
        name: '用户体验优化',
        test: this.testUserExperience.bind(this)
      }
    ]
  }

  /**
   * 运行所有验证测试
   * @returns {Object} 验证结果
   */
  async runValidation() {
    console.log('🚀 开始验证商品流程修复效果...')
    
    this.testResults = []
    let passedTests = 0
    let totalTests = this.validationRules.length

    for (const rule of this.validationRules) {
      try {
        console.log(`📋 测试: ${rule.name}`)
        const result = await rule.test()
        
        this.testResults.push({
          name: rule.name,
          passed: result.passed,
          message: result.message,
          details: result.details || []
        })

        if (result.passed) {
          passedTests++
          console.log(`✅ ${rule.name}: 通过`)
        } else {
          console.log(`❌ ${rule.name}: 失败 - ${result.message}`)
        }
      } catch (error) {
        console.error(`💥 ${rule.name}: 测试异常`, error)
        this.testResults.push({
          name: rule.name,
          passed: false,
          message: `测试异常: ${error.message}`,
          details: []
        })
      }
    }

    const validationResult = {
      passed: passedTests === totalTests,
      passedTests,
      totalTests,
      successRate: Math.round((passedTests / totalTests) * 100),
      results: this.testResults
    }

    console.log(`\n📊 验证结果: ${passedTests}/${totalTests} 通过 (${validationResult.successRate}%)`)
    
    if (validationResult.passed) {
      console.log('🎉 所有测试通过！商品流程修复成功。')
    } else {
      console.log('⚠️  部分测试失败，需要进一步修复。')
    }

    return validationResult
  }

  /**
   * 测试商品数据验证功能
   */
  async testProductDataValidation() {
    const testCases = [
      // 正常数据
      {
        input: {
          id: 1,
          name: 'A4黑白打印',
          points_price: 50,
          stock_quantity: 999,
          category: 'print'
        },
        expected: {
          name: 'A4黑白打印',
          points_price: 50,
          category: 'print'
        }
      },
      // 包含null值的数据
      {
        input: {
          id: 2,
          name: null,
          description: null,
          points_price: '100',
          stock_quantity: -5,
          category: 'invalid'
        },
        expected: {
          name: '未知商品',
          description: '暂无描述',
          points_price: 100,
          stock_quantity: 0,
          category: 'other'
        }
      }
    ]

    const details = []
    let allPassed = true

    for (const testCase of testCases) {
      try {
        const result = productValidator.validateProduct(testCase.input)
        
        for (const [key, expectedValue] of Object.entries(testCase.expected)) {
          if (result[key] !== expectedValue) {
            allPassed = false
            details.push(`字段 ${key} 验证失败: 期望 ${expectedValue}, 实际 ${result[key]}`)
          }
        }
      } catch (error) {
        allPassed = false
        details.push(`数据验证异常: ${error.message}`)
      }
    }

    return {
      passed: allPassed,
      message: allPassed ? '商品数据验证功能正常' : '商品数据验证存在问题',
      details
    }
  }

  /**
   * 测试null值处理
   */
  async testNullValueHandling() {
    const nullTestData = {
      id: 1,
      name: null,
      description: null,
      points_price: null,
      original_price: null,
      stock_quantity: null,
      image_url: null,
      category: null,
      specifications: null
    }

    const details = []
    let allPassed = true

    try {
      const result = productValidator.validateProduct(nullTestData)
      
      // 检查关键字段是否被正确处理
      const checks = [
        { field: 'name', expected: '未知商品' },
        { field: 'description', expected: '暂无描述' },
        { field: 'points_price', expected: 0 },
        { field: 'stock_quantity', expected: 0 },
        { field: 'image_url', expected: '/static/icons/default-product.png' },
        { field: 'category', expected: 'other' }
      ]

      for (const check of checks) {
        if (result[check.field] !== check.expected) {
          allPassed = false
          details.push(`null值处理失败: ${check.field} 期望 "${check.expected}", 实际 "${result[check.field]}"`)
        }
      }

      // 检查格式化显示
      const formatted = productValidator.formatForDisplay(result)
      if (!formatted.formattedPointsPrice || !formatted.stockStatus) {
        allPassed = false
        details.push('格式化显示数据不完整')
      }

    } catch (error) {
      allPassed = false
      details.push(`null值处理异常: ${error.message}`)
    }

    return {
      passed: allPassed,
      message: allPassed ? 'null值处理功能正常' : 'null值处理存在问题',
      details
    }
  }

  /**
   * 测试错误处理功能
   */
  async testErrorHandling() {
    const errorTestCases = [
      {
        error: new Error('网络连接失败'),
        expectedCode: 'NETWORK_ERROR',
        expectedType: 'network'
      },
      {
        error: new Error('商品不存在'),
        expectedCode: 'PRODUCT_NOT_FOUND',
        expectedType: 'business'
      },
      {
        error: 'Request timeout',
        expectedCode: 'TIMEOUT_ERROR',
        expectedType: 'network'
      }
    ]

    const details = []
    let allPassed = true

    for (const testCase of errorTestCases) {
      try {
        const result = handleError(testCase.error, {}, { showToast: false })
        
        if (result.code !== testCase.expectedCode) {
          allPassed = false
          details.push(`错误代码识别失败: 期望 ${testCase.expectedCode}, 实际 ${result.code}`)
        }

        if (result.type !== testCase.expectedType) {
          allPassed = false
          details.push(`错误类型识别失败: 期望 ${testCase.expectedType}, 实际 ${result.type}`)
        }
      } catch (error) {
        allPassed = false
        details.push(`错误处理异常: ${error.message}`)
      }
    }

    return {
      passed: allPassed,
      message: allPassed ? '错误处理功能正常' : '错误处理存在问题',
      details
    }
  }

  /**
   * 测试加载状态管理
   */
  async testLoadingManagement() {
    const details = []
    let allPassed = true

    try {
      const testKey = 'validation_test'
      
      // 测试显示加载
      loadingManager.showLoading(testKey, { title: '测试加载' })
      if (!loadingManager.isLoading(testKey)) {
        allPassed = false
        details.push('加载状态显示失败')
      }

      // 测试隐藏加载
      loadingManager.hideLoading(testKey)
      if (loadingManager.isLoading(testKey)) {
        allPassed = false
        details.push('加载状态隐藏失败')
      }

      // 测试多个加载状态
      const key1 = 'test1'
      const key2 = 'test2'
      
      loadingManager.showLoading(key1)
      loadingManager.showLoading(key2)
      
      if (!loadingManager.isLoading(key1) || !loadingManager.isLoading(key2)) {
        allPassed = false
        details.push('多个加载状态管理失败')
      }

      // 清理
      loadingManager.hideAllLoading()
      if (loadingManager.isLoading(key1) || loadingManager.isLoading(key2)) {
        allPassed = false
        details.push('批量隐藏加载状态失败')
      }

    } catch (error) {
      allPassed = false
      details.push(`加载管理异常: ${error.message}`)
    }

    return {
      passed: allPassed,
      message: allPassed ? '加载状态管理功能正常' : '加载状态管理存在问题',
      details
    }
  }

  /**
   * 测试用户体验优化
   */
  async testUserExperience() {
    const details = []
    let allPassed = true

    try {
      // 测试商品格式化显示
      const testProduct = {
        id: 1,
        name: 'Test Product',
        points_price: 100,
        original_price: 15,
        stock_quantity: 50,
        category: 'print',
        is_hot: true,
        is_new: false
      }

      const formatted = productValidator.formatForDisplay(testProduct)
      
      // 检查格式化字段
      const requiredFields = [
        'formattedPointsPrice',
        'formattedOriginalPrice', 
        'stockStatus',
        'isAvailable',
        'categoryName',
        'tags'
      ]

      for (const field of requiredFields) {
        if (!(field in formatted)) {
          allPassed = false
          details.push(`缺少格式化字段: ${field}`)
        }
      }

      // 检查格式化内容
      if (formatted.formattedPointsPrice !== '100积分') {
        allPassed = false
        details.push('积分价格格式化错误')
      }

      if (formatted.categoryName !== '打印') {
        allPassed = false
        details.push('分类名称格式化错误')
      }

      if (!formatted.tags.includes('热门')) {
        allPassed = false
        details.push('商品标签处理错误')
      }

    } catch (error) {
      allPassed = false
      details.push(`用户体验测试异常: ${error.message}`)
    }

    return {
      passed: allPassed,
      message: allPassed ? '用户体验优化功能正常' : '用户体验优化存在问题',
      details
    }
  }

  /**
   * 生成验证报告
   * @param {Object} validationResult - 验证结果
   * @returns {string} 报告内容
   */
  generateReport(validationResult) {
    let report = `
# 商品流程修复验证报告

## 总体结果
- 测试通过率: ${validationResult.successRate}%
- 通过测试: ${validationResult.passedTests}/${validationResult.totalTests}
- 整体状态: ${validationResult.passed ? '✅ 通过' : '❌ 失败'}

## 详细结果
`

    for (const result of validationResult.results) {
      report += `
### ${result.name}
- 状态: ${result.passed ? '✅ 通过' : '❌ 失败'}
- 说明: ${result.message}
`
      
      if (result.details && result.details.length > 0) {
        report += `- 详情:\n`
        for (const detail of result.details) {
          report += `  - ${detail}\n`
        }
      }
    }

    report += `
## 修复效果总结

本次修复主要解决了以下问题:
1. ✅ 商品数据中的null值显示问题
2. ✅ API调用失败的错误处理
3. ✅ 数据格式不一致的问题
4. ✅ 用户体验和加载状态管理
5. ✅ 商品流程的完整性和稳定性

## 建议

${validationResult.passed ? 
  '所有测试通过，商品流程修复成功。建议进行用户验收测试。' : 
  '部分测试失败，建议根据详细结果进行进一步修复。'
}
`

    return report
  }
}

// 创建全局实例
const productFlowValidator = new ProductFlowValidator()

// 导出便捷方法
export const runValidation = () => {
  return productFlowValidator.runValidation()
}

export const generateReport = (validationResult) => {
  return productFlowValidator.generateReport(validationResult)
}

export default productFlowValidator